import React, { Component } from 'react';
import ReactDom from 'react-dom';
class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      todolist : ["数据1","数据2","数据3","数据4","数据5"],
      inputValue : ''
    }
  }

  componentDidMount() {
    // 判断localStorage是否存在
    const list = localStorage.getItem("todolist");
    if (list && list.length !== 0) {
      this.setState({
        todolist:list.split(",")
      })
    }
  }

  // 监听输入框里面的内容
  inputChange = (e) => {
  //  console.log(e.target.value)
    this.setState({
      inputValue : e.target.value
    })
  }
  // 增加数据
  addItem = () => {
    if(this.state.inputValue === ''){
      alert("请输入内容！");
      return;
    }
    this.setState({
      todolist : [...this.state.todolist,this.state.inputValue],
      inputValue : ''
    })
    localStorage.setItem('todolist', [...this.state.todolist,this.state.inputValue]);
  }
  // 删除数据
  deleteItem = (index) => {
    let list = [...this.state.todolist];
    list.splice(index,1);
    this.setState({
      todolist : list
    })
    localStorage.setItem('todolist',list);
  }
  render() {
    return (
      <div>
        <input onChange={this.inputChange} value={this.state.inputValue}/><button onClick={this.addItem}>增加</button>
        <ul>
          {
            this.state.todolist.map((item,index) => {
              return <TodoItem item={item} key={index} index={index} deleteItem={this.deleteItem}/>
            })
          }
        </ul>
      </div>
    );
  }
}

class TodoItem extends Component {
  deleteItem = () => {
    this.props.deleteItem(this.props.index);
  }
  render(){
    return(
      <li>
        {this.props.item}
        <button onClick={this.deleteItem}>删除</button>
      </li>
    )
  }
}

ReactDom.render(<App />,document.getElementById("root"));

export default App;
